{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    }
   ],
   "source": [
    "###  COPY ALL THE CODE INTO A JYPYTER NOTEBOOK  ### \n",
    "###  THE JYPYTER NOTEBOOK NEEDS TO BE IN 'tensorflow\\models\\research\\deeplab'  ### \n",
    "\n",
    "## Imports\n",
    "\n",
    "import collections\n",
    "import os\n",
    "import io\n",
    "import sys\n",
    "import tarfile\n",
    "import tempfile\n",
    "import urllib\n",
    "\n",
    "from IPython import display\n",
    "from ipywidgets import interact\n",
    "from ipywidgets import interactive\n",
    "from matplotlib import gridspec\n",
    "from matplotlib import pyplot as plt\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import cv2\n",
    "# import skvideo.io\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "# Needed to show segmentation colormap labels\n",
    "sys.path.append('utils')\n",
    "import get_dataset_colormap\n",
    "from deeplabv3_model import Deeplabv3\n",
    "\n",
    "os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Load model in keras\n",
    "\n",
    "deeplab_model = Deeplabv3()\n",
    "\n",
    "\n",
    "\n",
    "## Webcam demo\n",
    "\n",
    "cap = cv2.VideoCapture(0)\n",
    "\n",
    "# Next line may need adjusting depending on webcam resolution\n",
    "final = np.zeros((1, 384, 1026, 3))\n",
    "while True:\n",
    "    ret, frame = cap.read()\n",
    "    \n",
    "    # From cv2 to PIL\n",
    "    cv2_im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n",
    "    img = Image.fromarray(cv2_im)\n",
    "    img = np.array(img)\n",
    "    w, h, _ = img.shape\n",
    "    ratio = 512. / np.max([w,h])\n",
    "    resized = cv2.resize(img,(int(ratio*h),int(ratio*w)))\n",
    "    resized = resized / 127.5 - 1.\n",
    "    pad_x = int(512 - resized.shape[0])\n",
    "    resized2 = np.pad(resized,((0,pad_x),(0,0),(0,0)),mode='constant')\n",
    "    res = deeplab_model.predict(np.expand_dims(resized2,0))\n",
    "    seg_map = np.argmax(res.squeeze(),-1)[:-pad_x]\n",
    "    \n",
    "    # Adjust color of mask\n",
    "    seg_image = get_dataset_colormap.label_to_color_image(\n",
    "        seg_map, get_dataset_colormap.get_pascal_name()).astype(np.uint8)\n",
    "    \n",
    "\n",
    "#     # Run model\n",
    "#     seg_map = deeplab_model.predict(pil_im)\n",
    "#     print(seg_map.shape)\n",
    "    \n",
    "#     # Adjust color of mask\n",
    "#     seg_image = get_dataset_colormap.label_to_color_image(\n",
    "#         seg_map, get_dataset_colormap.get_pascal_name()).astype(np.uint8)\n",
    "    \n",
    "#     # Convert PIL image back to cv2 and resize\n",
    "#     frame = np.array(pil_im)\n",
    "#     r = seg_image.shape[1] / frame.shape[1]\n",
    "#     dim = (int(frame.shape[0] * r), seg_image.shape[1])[::-1]\n",
    "#     resized = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)\n",
    "#     masked_map = np.array(seg_image, copy=True)\n",
    "#     for i in range(int(frame.shape[0] * r)):\n",
    "#         for j in range(seg_image.shape[1]):\n",
    "            \n",
    "#             if seg_map[i][j] == 5:\n",
    "#                 for k in range(3):\n",
    "#                     masked_map[i][j][k] = resized[i][j][k]\n",
    "#             else:\n",
    "#                 masked_map[i][j][0] = 0\n",
    "#     resized = cv2.cvtColor(resized, cv2.COLOR_RGB2BGR)\n",
    "#     masked_image = cv2.cvtColor(masked_map, cv2.COLOR_RGB2BGR)\n",
    "    \n",
    "    # Stack horizontally color frame and mask\n",
    "    color_and_mask = np.hstack((resized, seg_image))\n",
    "    cv2.imshow('frame', color_and_mask)\n",
    "    if cv2.waitKey(25) & 0xFF == ord('q'):\n",
    "        cap.release()\n",
    "        cv2.destroyAllWindows()\n",
    "        break\n",
    "\n",
    "    \n",
    "###  UNCOMMENT NEXT LINES TO SAVE THE VIDEO  ###\n",
    "#    output = np.expand_dims(both, axis=0)\n",
    "#    final = np.append(final, output, 0)\n",
    "#skvideo.io.vwrite(\"outputvideo111.mp4\", final)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
